from rest_framework import serializers
from api import models
from rest_framework import exceptions


class OrderModelSerializer(serializers.ModelSerializer):
    cover = serializers.CharField(source='item.cover')
    title = serializers.CharField(source='item.title')
    create_date = serializers.DateTimeField(format="%Y-%d-%m %H:%M")

    class Meta:
        model = models.Order
        fields = ['title', 'cover', 'id', 'price', 'create_date', 'status']


class CouponModelSerializer(serializers.ModelSerializer):
    # apply_start_date = serializers.DateTimeField(format="%Y-%d-%m %H:%M")
    # apply_stop_date = serializers.DateTimeField(format="%Y-%d-%m %H:%M")
    status_name = serializers.CharField(source='get_status_display', read_only=True)
    cover = serializers.CharField(source='auction.cover', read_only=True)
    remain = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = models.Coupon
        exclude = ['deleted', 'auction']

    def get_remain(self, obj):
        return obj.count - obj.apply_count


class UserCouponModelSerializer(serializers.ModelSerializer):
    remain = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = models.UserCoupon
        fields = ['remain', 'coupon']

    def validate_coupon(self, value):

        user_object = self.context['request'].user
        # 优惠券不存在
        if not value or value.deleted:
            raise exceptions.ValidationError('优惠券不存在')

        # 优惠券状态必须是领取中
        if value.status != 2:
            raise exceptions.ValidationError('优惠券不可领取')

        # 优惠券个数是否合法
        if (value.apply_count + 1) > value.count:
            raise exceptions.ValidationError('优惠券已领完')

        # 是否已领取优惠券
        exists = models.UserCoupon.objects.filter(user=user_object, coupon=value).exists()
        if exists:
            raise exceptions.ValidationError('已领取此优惠券')

        return value

    def get_remain(self, obj):
        return obj.coupon.count - obj.coupon.apply_count - 1


class MyUserCouponModelSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display')
    coupon = serializers.CharField(source='coupon.title')
    cover = serializers.CharField(source='coupon.auction.cover')
    money = serializers.CharField(source='coupon.money')

    class Meta:
        model = models.UserCoupon
        fields = "__all__"


class AddressModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Address
        exclude = ['user']
